import React, {
  useCallback, useEffect, useMemo, useState,
} from 'react'
import {
  Text, TouchableOpacity, View,
} from 'react-native'
import BleManager from '@UTILS/BleManager'
import Permissions from '@UTILS/Permissions'
import { State } from 'react-native-ble-plx'
import BluetoothStateManager from 'react-native-bluetooth-state-manager'
import { isIOS } from '@UTILS/Common'
import Toast from '@COMPONENTS/Toast'
import CustomerService from '@COMPONENTS/modal/CustomerService'
import Dialog from '@COMPONENTS/Dialog'
import AnalyticsUtil, { ANALYTICS_EVENT } from '@UTILS/AnalyticsUtil'
import BleDeviceFunctionality from '@UTILS/BleDeviceFunctionality'
import EStyleSheet from 'react-native-extended-stylesheet'

interface StatusItem {
  desc: string,
  btnText: string
}

const Status: { [key in (State)]?: StatusItem } = {
  [State.Unauthorized]: { desc: '未授权', btnText: '开启蓝牙' },
  [State.PoweredOff]: { desc: '未开启', btnText: '开启蓝牙' },
  [State.PoweredOn]: { desc: '已开启蓝牙', btnText: '搜索设备' },
  [State.Unknown]: { desc: '未知', btnText: '请稍后' },
  [State.Resetting]: { desc: '正在重置...', btnText: '请稍后' },
  [State.Unsupported]: { desc: '不支持', btnText: '不支持' },
}

const Demo: React.FC = () => {
  const bleDevice = useMemo(() => new BleDeviceFunctionality(), [])
  const [bleState, setBleState] = useState<State>()
  const testBle = useCallback(async () => {
    switch (bleState) {
      case State.PoweredOn: {
        console.log('grantedgrantedgranted')
        // android 需要额外权限
        const p = await Permissions.allPrerequisitesOK()
        console.log('grantedgrantedgranted22')

        if (!isIOS && !p) {
          const granted = await Permissions.requestBluPermission()
          console.log('grantedgrantedgranted', granted)
          if (!granted) {
            setBleState(State.Unauthorized)
            return
          }
          BleManager.connect(null, (error1, info1) => {
            console.log('infoinfoinfo22', error1, info1)
          })
        } else {
          BleManager.connect(null, (error1, info1) => {
            console.log('infoinfoinfo22', error1, info1)
          })
        }

        break
      }
      case State.PoweredOff: {
        if (isIOS) {
          BluetoothStateManager.openSettings()
        } else {
          BluetoothStateManager.enable()
        }
        break
      }
      case State.Unauthorized: {
        break
      }
      default: {
        break
      }
    }
  }, [bleState])
  useEffect(() => {
    BleManager.init()
    console.log('11111111111', Permissions.isEnabledBlu())
    const sub = BleManager.onStateChange(async (newState) => {
      console.log('onStateChange', newState, State)
      const p = await Permissions.isEnabledBlu()
      if (isIOS && !p) {
        setBleState(State.Unauthorized)
        return
      }
      setBleState(newState)
    }, true)
    return () => {
      console.log('useEffectremove')
      BleManager.remove(sub)
      BleManager.stopDeviceScan()
    }
  }, [])
  const bleCON = bleState ? Status[bleState] : {} as StatusItem
  console.log('bleState', bleState, bleCON)

  return (
    <View style={styles.container}>
      <Text style={styles.lineWidth}>
        { `蓝牙状态：${bleCON?.desc}` }
      </Text>
      <TouchableOpacity onPress={testBle} style={styles.btn}>
        <Text>
          { bleCON?.btnText }
        </Text>
      </TouchableOpacity>
      <TouchableOpacity
        onPress={() => {
          bleDevice.clearPassword()
        }}
        style={styles.btn}
      >
        <Text>清楚密码</Text>
      </TouchableOpacity>
      <TouchableOpacity
        style={styles.btn}
        onPress={() => {

        }}
      >
        <Text> 测试thunk </Text>
      </TouchableOpacity>
      <TouchableOpacity
        style={styles.btn}
        onPress={() => {
          AnalyticsUtil.onEvent(ANALYTICS_EVENT.tap_device_maintenance.eventId)
          Toast.info('请先阅读并同意《纳瑞维用户协议》及\n《隐私政策》')
        }}
      >
        <Text> 测试Toast info </Text>
      </TouchableOpacity>
      <TouchableOpacity
        style={styles.btn}
        onPress={() => {
          CustomerService.show()
        }}
      >
        <Text> 测试CustomerService </Text>
      </TouchableOpacity>
      <TouchableOpacity
        style={styles.btn}
        onPress={() => {
          Toast.success('请求成功')
        }}
      >
        <Text> 成功Toast info </Text>
      </TouchableOpacity>
      <TouchableOpacity
        style={styles.btn}
        onPress={() => {
          const key = Dialog.show({
            content: '确认注销当前账户吗？',
            title: '提示',
            autoRemove: false,
            onConfirm: () => {
              Dialog.remove(key)
              // CustomerService.show()
              Toast.success('请求成功')

              console.log('onConfirm')
            },
          })
        }}
      >
        <Text> Dialog </Text>
      </TouchableOpacity>
    </View>
  )
}
const styles = EStyleSheet.create({
  container: {
    display: 'flex',
    flexDirection: 'row',
    flexWrap: 'wrap',
  },
  lineWidth: {
    width: '100%',
  },
  btn: {
    margin: 16,
    padding: 12,
    backgroundColor: '$theme',
  },
})
export default Demo
